package com.zhuchaooasystem.ui.home.service;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.hwangjr.rxbus.RxBus;
import com.zhuchaooasystem.R;
import com.zhuchaooasystem.base.BaseActivity;
import com.zhuchaooasystem.base.BaseEvent;
import com.zhuchaooasystem.common.Key;
import com.zhuchaooasystem.entity.ServiceDetailEntity;
import com.zhuchaooasystem.entity.ServicePeopleEntity;
import com.zhuchaooasystem.entity.ServiceRedactAlterEntity;
import com.zhuchaooasystem.entity.UserInfo;
import com.zhuchaooasystem.event.ServiceDetailEvent;
import com.zhuchaooasystem.presenter.home.serviceradect.ServiceRadectContract;
import com.zhuchaooasystem.presenter.home.serviceradect.ServiceRadectPresenter;
import com.zhuchaooasystem.utils.CalendarUtils;
import com.zhuchaooasystem.utils.StringUtils;
import com.zhuchaooasystem.widget.PurchaseDialog;
import com.zhuchaooasystem.widget.StateButton;

import butterknife.BindView;
import butterknife.OnClick;

public class ServiceRadectActivity extends BaseActivity<ServiceRadectPresenter>
        implements ServiceRadectContract.View {


    @BindView(R.id.actionbar_iv_back)
    ImageView actionbarIvBack;
    @BindView(R.id.actionbar_txt_title)
    TextView actionbarTxtTitle;
    @BindView(R.id.act_service_radect_code)
    TextView actServiceRadectCode;
    @BindView(R.id.act_service_radect_name)
    TextView actServiceRadectName;
    @BindView(R.id.act_service_radect_appointment_date)
    TextView actServiceRadectAppointmentDate;
    @BindView(R.id.act_service_radect_appointment_time)
    TextView actServiceRadectAppointmentTime;
    @BindView(R.id.act_service_radect_service_people)
    TextView actServiceRadectServicePeople;
    @BindView(R.id.act_service_radect_et)
    EditText actServiceRadectEt;
    @BindView(R.id.fragmelayout_service_radect_blank_view)
    View fragmelayoutServiceRadectBlankView;
    @BindView(R.id.fragmelayout_service_radect_content_layout)
    LinearLayout fragmelayoutServiceRadectContentLayout;
    @BindView(R.id.fragmelayout_service_radect_service_people_layout)
    FrameLayout fragmelayoutServiceRadectServicePeopleLayout;
    @BindView(R.id.fragmelayout_service_radect_complete_tv)
    TextView fragmelayoutServiceRadectCompleteTv;
    @BindView(R.id.act_service_radect_appointment_date_layout)
    LinearLayout actServiceRadectAppointmentDateLayout;
    @BindView(R.id.act_service_radect_appointment_time_layout)
    LinearLayout actServiceRadectAppointmentTimeLayout;
    @BindView(R.id.act_service_radect_service_people_layout)
    LinearLayout actServiceRadectServicePeopleLayout;

    @BindView(R.id.fragmelayout_service_radect_layout)
    RelativeLayout fragmelayoutServiceRadectLayout;
    @BindView(R.id.activity_service_radect)
    RelativeLayout activityServiceRadect;
    @BindView(R.id.act_service_radect_btn_complete)
    StateButton actServiceRadectBtnComplete;
    @BindView(R.id.act_service_radect_purchase)
    TextView actServiceRadectPurchase;


    private ServiceDetailEntity.ResultBean.SuccessfulBean bean;

    private PurchaseDialog dialog;

    private Resources resource;
    private ColorStateList csl;
    private String date = "";
    private String time = "";
    private String today;
    private String FlowRemark = "";
    private String FormatCode = "";
    //服务人
    private StringBuffer servicePeople = new StringBuffer();
    //服务人id
    private StringBuffer servicePeopleID = new StringBuffer();


    @Override
    protected int getLayout() {
        return R.layout.activity_service_radect;
    }

    @Override
    protected ServiceRadectPresenter getPresenter() {
        return new ServiceRadectPresenter(mContext, this);
    }

    @Override
    protected void initVariables() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        bean = (ServiceDetailEntity.ResultBean.SuccessfulBean)
                bundle.getSerializable(Key.SERVICE_DETAIL_ENTITY);
        today = CalendarUtils.getNow("yyyy/MM/dd HH:mm:ss");
    }

    @Override
    protected void initView() {

        resource = (Resources) getBaseContext().getResources();

        actionbarTxtTitle.setText("编辑服务");
        actionbarIvBack.setVisibility(View.VISIBLE);

        actServiceRadectCode.setText(bean.getAnonymousModel().getOrderCode());
        actServiceRadectName.setText(bean.getAnonymousModel().getServerName());
        String reservation = bean.getServiceModel().getReservation();
        if (!TextUtils.isEmpty(reservation)) {
            String[] reservationStr = reservation.split(" ");
            if (null != reservationStr && reservationStr.length == 2) {
                date = reservationStr[0].replace("-", "/");
                time = reservationStr[1].replace("-", "/");
                actServiceRadectAppointmentDate.setText(date);
                actServiceRadectAppointmentTime.setText(time);
            } else {
                date = today.split(" ")[0];
                time = today.split(" ")[1];
                actServiceRadectAppointmentDate.setText("暂无");
                actServiceRadectAppointmentTime.setText("暂无");
            }
        } else {
            date = today.split(" ")[0];
            time = today.split(" ")[1];
            actServiceRadectAppointmentDate.setText("暂无");
            actServiceRadectAppointmentTime.setText("暂无");
        }
        actServiceRadectServicePeople.setText(bean.getServiceModel().getServicePeople());
        actServiceRadectEt.setText(bean.getServiceModel().getServiceRemark());

        //采购单号
        if (TextUtils.isEmpty(bean.getAnonymousModel().getPurchaseId())) {
            actServiceRadectPurchase.setText("未绑定");
        } else {
            actServiceRadectPurchase.setText(bean.getAnonymousModel().getPurchaseId());
        }

        mPresenter.downServicePeople(bean.getAnonymousModel().getID() + "");

    }

    @Override
    protected void initDataAndLoadData() {

    }

    @OnClick({R.id.actionbar_iv_back, R.id.act_service_radect_appointment_date_layout, R.id.act_service_radect_appointment_time_layout,
            R.id.act_service_radect_service_people_layout, R.id.act_service_radect_purchase_code_layout, R.id.fragmelayout_service_radect_blank_view,
            R.id.fragmelayout_service_radect_complete_tv, R.id.act_service_radect_btn_complete,
            R.id.fragmelayout_service_radect_layout, R.id.act_service_radect_purchase})
    public void onClick(View view) {
        switch (view.getId()) {
            //返回
            case R.id.actionbar_iv_back:
                ServiceRadectActivity.this.finish();
                break;
            //日期
            case R.id.act_service_radect_appointment_date_layout:
                new DatePickerDialog(ServiceRadectActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        date = year + "/" + (monthOfYear + 1) + "/" + dayOfMonth;
                        actServiceRadectAppointmentDate.setText(date);

                    }
                }, Integer.parseInt(date.split("/")[0]), (Integer.parseInt(date.split("/")[1]) - 1), Integer.parseInt(date.split("/")[2])).show();

                break;
            //时间
            case R.id.act_service_radect_appointment_time_layout:
                new TimePickerDialog(ServiceRadectActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        time = hourOfDay + ":" + minute;
                        actServiceRadectAppointmentTime.setText(time);
                    }
                }, Integer.parseInt(time.split(":")[0]), Integer.parseInt(time.split(":")[1]), true).show();
                break;
            //服务人
            case R.id.act_service_radect_service_people_layout:
                if (fragmelayoutServiceRadectServicePeopleLayout.isShown()) {
                    fragmelayoutServiceRadectServicePeopleLayout.startAnimation(AnimationUtils.loadAnimation(ServiceRadectActivity.this,
                            R.anim.slide_out_right));
                    fragmelayoutServiceRadectServicePeopleLayout.setVisibility(View.GONE);
                } else {
                    //打开抽屉的时候清空数据   并且每次进入抽屉CheckBox都是未选中状态
                    servicePeople.delete(0, servicePeople.length());
                    servicePeopleID.delete(0, servicePeopleID.length());
                    for (int i = 0; i < fragmelayoutServiceRadectContentLayout.getChildCount(); i++) {
                        CheckBox checkBox = (CheckBox) fragmelayoutServiceRadectContentLayout.getChildAt(i);
                        checkBox.setChecked(false);
                    }

                    fragmelayoutServiceRadectServicePeopleLayout.startAnimation(AnimationUtils.loadAnimation(ServiceRadectActivity.this,
                            R.anim.slide_in_right));
                    fragmelayoutServiceRadectServicePeopleLayout.setVisibility(View.VISIBLE);
                }
                break;
            //点击空白区域 抽屉隐藏
            case R.id.fragmelayout_service_radect_blank_view:
                if (fragmelayoutServiceRadectServicePeopleLayout.isShown()) {
                    fragmelayoutServiceRadectServicePeopleLayout.startAnimation(AnimationUtils.loadAnimation(ServiceRadectActivity.this,
                            R.anim.slide_out_right));
                    fragmelayoutServiceRadectServicePeopleLayout.setVisibility(View.GONE);
                }
                break;
            case R.id.fragmelayout_service_radect_layout:
                break;
            //抽屉的完成
            case R.id.fragmelayout_service_radect_complete_tv:

                if (servicePeople.toString() == null || servicePeople.toString().equals("")) {
                    Toast.makeText(mContext, "请选择服务人", Toast.LENGTH_SHORT).show();
                } else {

                    actServiceRadectServicePeople.setText(StringUtils.deleteLastStr(servicePeople.toString()));

                    if (fragmelayoutServiceRadectServicePeopleLayout.isShown()) {
                        fragmelayoutServiceRadectServicePeopleLayout.startAnimation(AnimationUtils.loadAnimation(ServiceRadectActivity.this,
                                R.anim.slide_out_right));
                        fragmelayoutServiceRadectServicePeopleLayout.setVisibility(View.GONE);
                    }
                }


                break;
            //采购单
            case R.id.act_service_radect_purchase_code_layout:
                if (bean.getAnonymousModel().isIsInternal()) {
                    dialog = new PurchaseDialog(ServiceRadectActivity.this);
                    dialog.show();
                    //解决editview无法打开软键盘
                    dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                    //点击其他区域不消失
                    dialog.setCanceledOnTouchOutside(false);

                    dialog.setTextTitle("采购单号");

                    dialog.setOnViewClickListener(new PurchaseDialog.OnViewClickListener() {
                        @Override
                        public void onClickOk(String str) {
                            if (str != null && (!str.equals(""))) {

                                actServiceRadectPurchase.setText(str);
                                csl = (ColorStateList) resource.getColorStateList(R.color.color_1bc3ad);
                                actServiceRadectPurchase.setTextColor(csl);
                            }
                            dialog.dismiss();
                        }

                        @Override
                        public void onClickCancel(PurchaseDialog dialog) {
                            dialog.dismiss();
                        }
                    });


                } else {
                    Toast.makeText(mContext, "无绑定采购单权限", Toast.LENGTH_SHORT).show();
                }
                break;
            //完成编辑
            case R.id.act_service_radect_btn_complete:
                //备注
                if (actServiceRadectEt.getText().toString() == null ||
                        actServiceRadectEt.getText().toString().equals("")) {
                    FlowRemark = "";
                } else {
                    //如果备注没有改变就提交null
                    if (actServiceRadectEt.getText().toString().
                            equals(bean.getServiceModel().getServiceRemark())) {
                        FlowRemark = "";
                    } else {
                        FlowRemark = actServiceRadectEt.getText().toString().trim();

                    }
                }

                //采购单号
                if (actServiceRadectPurchase.getText().equals("未绑定")) {
                    FormatCode = "";
                } else {
                    FormatCode = actServiceRadectPurchase.getText().toString().trim();
                }

                //编辑完成
                if (servicePeople.toString() == null || servicePeople.toString().equals("")) {

                    mPresenter.alterServiceRedact(bean.getAnonymousModel().getID() + "", date + " " + time,
                            "", UserInfo.getPersonalPk() + "",
                            UserInfo.getUName(), FlowRemark, FormatCode);
                } else {

                    mPresenter.alterServiceRedact(bean.getAnonymousModel().getID() + "", date + " " + time,
                            StringUtils.deleteLastStr(servicePeopleID.toString()), UserInfo.getPersonalPk() + "",
                            UserInfo.getUName(), FlowRemark, FormatCode);

                }

                break;
        }
    }

    /**
     * 获取服务人
     *
     * @param entity
     */
    @Override
    public void showServicePeople(final ServicePeopleEntity entity) {
        //抽屉里面的内容添加
        for (int i = 0; i < entity.getResult().getSuccessful().size(); i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.activity_service_radect_framelayout_content, null);
            final CheckBox checkBox = (CheckBox) view.findViewById(R.id.act_service_radect_framelayout_content_cb);
            checkBox.setText(entity.getResult().getSuccessful().get(i).getName());

            fragmelayoutServiceRadectContentLayout.addView(checkBox);

            //checkbox选中则添加字符串，取消选中则删除字符串
            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if (b) {

                        servicePeople.append(compoundButton.getText().toString() + ",");
                        //添加服务人ID
                        for (int j = 0; j < entity.getResult().getSuccessful().size(); j++) {
                            if (entity.getResult().getSuccessful().get(j).getName().
                                    equals(compoundButton.getText().toString())) {

                                servicePeopleID.append(entity.getResult().getSuccessful().get(j).getUid() + ",");

                            }
                        }


                    } else {
                        if (servicePeople.toString() == null || servicePeople.toString().equals("")) {

                        } else {
                            //做删除操作
                            String str = servicePeople.toString();
                            String[] ss = str.split(",");

                            String strID = servicePeopleID.toString();
                            String[] ssID = strID.split(",");

                            if (ss.length > 1) {
                                //清空
                                servicePeople.delete(0, servicePeople.length());

                                servicePeopleID.delete(0, servicePeopleID.length());

                                for (int i = 0; i < ss.length - 1; i++) {
                                    servicePeople.append(ss[i] + ",");

                                    servicePeopleID.append(ssID[i] + ",");
                                }

                            } else {
                                //清空
                                servicePeople.delete(0, servicePeople.length());

                                servicePeopleID.delete(0, servicePeopleID.length());
                            }

                        }
                    }
                }
            });

        }
    }

    @Override
    public void showAlterResult(ServiceRedactAlterEntity entity) {

        if (!(entity.getResult().getSuccessful() == null || entity.getResult().getSuccessful().equals(""))) {
            Toast.makeText(mContext, entity.getResult().getSuccessful(), Toast.LENGTH_SHORT).show();

            //RxBus发送通知，ButtonOnClick这个是自己随便定义的一个tag，
            // 也就是一个标志，用来让接收通知的类识别的
            //BtnEvent是自己定义的一个事件，里面包含了需要传递的数据
            RxBus.get().post("RedactFinish", new ServiceDetailEvent());
            RxBus.get().post("reservation", new BaseEvent<>());

            ServiceRadectActivity.this.finish();
        }

        if (!(entity.getResult().getError() == null || entity.getResult().getError().equals(""))) {
            Toast.makeText(mContext, entity.getResult().getError(), Toast.LENGTH_SHORT).show();
        }
    }
}
